import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

import '../../services/screen_adapter.dart';
import '../../model/cate_model.dart';
import '../../config/config.dart';

class CategoryPage extends StatefulWidget {
  CategoryPage({Key key}) : super(key: key);

  @override
  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> with AutomaticKeepAliveClientMixin {
  
  int _selectIndex = 0;
  List _leftCateList = [];
  List _rightCateList = [];

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() { 
    super.initState();
    _getLeftCateData();
  }

  // 左侧分类
  _getLeftCateData() async{
    var api = "${Config.domain}api/pcate";
    var result = await Dio().get(api);
    var leftCateList = CateModel.fromJson(result.data);

    setState(() => this._leftCateList = leftCateList.result);
    _getRightCateData(leftCateList.result[0].sId);
  }

  // 右侧分类
  _getRightCateData(pid) async{
    var api = "${Config.domain}api/pcate?pid=$pid";
    var result = await Dio().get(api);
    var rightCateList = CateModel.fromJson(result.data);

    setState(() => this._rightCateList = rightCateList.result);
  }

  Widget _leftWidget(leftWidth) {

    if(this._leftCateList.length > 0) {
      return Container(
        width: leftWidth,
        height: double.infinity,
        child: ListView.builder(
          itemCount: _leftCateList.length,
          itemBuilder: (context, index) {
            return Column(
              children: <Widget>[
                InkWell(
                  onTap: (){
                    setState(() => _selectIndex = index);
                    this._getRightCateData(this._leftCateList[index].sId);
                  },
                  child: Container(
                    width: double.infinity,
                    height: ScreenAdapter.height(84),
                    padding: EdgeInsets.only(top: ScreenAdapter.height(24)),
                    child: Text('${this._leftCateList[index].title}', textAlign: TextAlign.center),
                    color: _selectIndex==index ? Color.fromRGBO(240, 246, 246, 0.9) : Colors.white,
                  ) 
                ),
                Divider(height: 1)
              ], 
            );
          }
        )
      );
    }else {
      return Container(
        width: leftWidth,
        height: double.infinity
      );  
    }

    } 
    

  Widget _rightWidget(rightItemWidth, rightItemHeight) {
    
    if(this._rightCateList.length > 0) {
      return Expanded(
        flex: 1,
        child: Container(
          padding: EdgeInsets.all(10),
          height: double.infinity,
          color: Color.fromRGBO(240, 246, 246, 0.9),
          child: GridView.builder( // 动态GridView
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3, // 列数量
              childAspectRatio: rightItemWidth/rightItemHeight, // 宽高比,为适应不同设备，需要进行计算
              crossAxisSpacing: 10, // 主轴
              mainAxisSpacing: 10 // 纵轴
            ),
            itemCount: this._rightCateList.length,
            itemBuilder: (context, index) {
              
              // 处理图片
              String pic = this._rightCateList[index].pic;
              pic = Config.domain + pic.replaceAll('\\', '/');

              return InkWell(
                onTap: () {
                  Navigator.pushNamed(context, '/productList', arguments: {
                    'cid': this._rightCateList[index].sId
                  });
                },
                child: Container(
                  child: Column(
                    children: <Widget>[
                      AspectRatio(
                        aspectRatio: 1/1, //配置图片的宽高比
                        child: Image.network("$pic", fit: BoxFit.cover)
                      ),
                      Container(
                        height: ScreenAdapter.height(28),
                        child: Text('${this._rightCateList[index].title}') 
                      )
                    ],
                  )
                ) 
              );
            }
          )
        )
      );
    } else {
      return Expanded(
        flex: 1,
        child: Container(
          padding: EdgeInsets.all(10),
          height: double.infinity,
          color: Color.fromRGBO(240, 246, 246, 0.9),
          child: Text('加载中...')
        )
      );    
    }
    
  }

  @override
  Widget build(BuildContext context) {

    // 注意用ScreenAdaper必须得在build方法里面初始化
    ScreenAdapter.init();

    // 计算右侧GridView宽高比
    var leftWidth = ScreenAdapter.getScreenWidth() / 4;

    // 右侧每一项的宽度 = （总宽度-左侧宽度-GridView外层元素左右Padding值-GridView中间间距）/3
    var rightItemWidth = (ScreenAdapter.getScreenWidth() - leftWidth - 20 - 20) / 3;
    // 计算后的宽度
    rightItemWidth = ScreenAdapter.width(rightItemWidth);
    // 计算后的高度
    var rightItemHeight = rightItemWidth + ScreenAdapter.height(28);

    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(Icons.center_focus_weak, size: 28, color: Colors.black87), 
          onPressed: null
        ),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.message, size: 28, color: Colors.black87), 
            onPressed: null
          )
        ],
        title: InkWell(
          onTap: () {
            Navigator.pushNamed(context, '/search');
          },
          child: Container(
            height: ScreenAdapter.height(68),
            decoration: BoxDecoration(
              color: Color.fromRGBO(233, 233, 233, 0.8),
              borderRadius: BorderRadius.circular(30)
            ),
            padding: EdgeInsets.only(left: 10),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Icon(Icons.search),
                Text('笔记本', style: TextStyle(
                  fontSize: ScreenAdapter.size(28)
                ))
              ],
            )
          )
        ) 
      ),
      body: Row(
        children: <Widget>[
          //左侧
          _leftWidget(leftWidth),
          //右侧
          _rightWidget(rightItemWidth, rightItemHeight)
        ],
      )
    );
  }


}